<?php
namespace app\members\controller;
use app\index\controller\Log\InsertLog as IL;
use app\index\controller\Log\OperationLog as OL;
use think\Controller;
use think\Db;
use think\Request;

//操作类型：1增加2修改3禁用4删除5登录6登出7导出8待添加
// use app\common\Option;
class Index extends Controller {
	public function __construct() {
		parent::_initialize();

	}
	public function index() {
		echo "你走错门了 O(∩_∩)O ！";
		exit;
	}

	/**
	 * 刘家腾
	 * 2018-5-7
	 * 禁用员工
	 */
	public function staff_disabled() {
		$data['code'] = 666;
		$data['msg'] = "操作成功！";
		$data['data'] = '';
		$params = input('post.');

		$validate = [
			"id|员工id" => "require",
		];

		if ($this->validate($params, $validate) !== true) {
			return ['code' => 30003, 'msg' => '员工id不能为空'];
		}

		$staff = Db::table('staff')->where(['user_id' => $params['id']])->find();
		if ($staff['state'] == 0) {
			$fettle = Db::table('staff')->where(['user_id' => $params['id']])->update(['state' => '1']);
		} else {
			$fettle = Db::table('staff')->where(['user_id' => $params['id']])->update(['state' => '0']);
		}
		if ($fettle != 1) {
			$data['code'] = 30018;
			$data['msg'] = "操作失败！";
			$data['data'] = '';
		}
		if ($data['code'] == 666) {
			OL::insert([
				'user_id' => $this->user_id,
				'module' => 'staff',
				'module_id' => $params['id'],
				'operation_type' => 3, //操作类型：1增加2修改3禁用4删除5登录6登出7导出8待添加
				'operation_content' => json_encode(['staff' => Db::table('staff')->where(['user_id' => $params['id']])->find()]),
			]);
		}
		return $data;
	}
	/**
	 * 刘家腾
	 * 2018-5-7
	 * 删除员工
	 */
	public function staff_delete() {
		$data['code'] = 666;
		$data['msg'] = "操作成功！";
		$data['data'] = '';
		$params = input('post.');

		$validate = [
			"id|员工id" => "require",
		];

		if ($this->validate($params, $validate) !== true) {
			return ['code' => 30003, 'msg' => '员工id不能为空'];
		}

		$fettle = Db::table('staff')->where(['user_id' => $params['id']])->update(['is_delete' => '1']);
		if ($fettle != 1) {
			$data['code'] = 30018;
			$data['msg'] = "操作失败！";
			$data['data'] = '';
		}
		if ($data['code'] == 666) {
			OL::insert([
				'user_id' => $this->user_id,
				'module' => 'staff',
				'module_id' => $params['id'],
				'operation_type' => 4,
				'operation_content' => json_encode(['staff' => Db::table('staff')->where(['user_id' => $params['id']])->find()]),
			]);
		}
		return $data;
	}
	/**
	 * 刘家腾
	 * 2018-5-7
	 * 图片上传类（单图 file名不固定）
	 */
	public function uploadedfile() {

		$request = Request::instance();
		// 接收文件
		$keys = array_keys($_FILES);
		$key = $keys['0'];
		$file = $_FILES[$key];

		// 先判断有没有错
		if ($file["error"] == 0) {
			$typeArr = explode("/", $file["type"]);

			if ($typeArr[0] == "image") {
				$imgType = array("png", "jpg", "jpeg");

				if (in_array($typeArr[1], $imgType)) {
					$url = $_SERVER['DOCUMENT_ROOT'] . "/api/public/uploads/";
					if (!is_dir($url . date("Y-m-d"))) {
						mkdir($url . date("Y-m-d"), 0777, true);
					}
					$imgname = "";
					$imgurl = "";
					$map = array();
					$imgname = time() . "." . $typeArr[1];
					$imgurl = $url . date("Y-m-d") . '/' . $imgname;
					$imgurls = $request->domain() . "/api/public/uploads/" . date("Y-m-d") . '/' . $imgname;
					$bol = move_uploaded_file($file["tmp_name"], $imgurl);
					$image = \think\Image::open($imgurl);
					$image_files = substr($imgurl, 0, strripos($imgurl, '.'));
					$image_file = substr($image_files, strrpos($imgurl, 'api') - 1);
					$image->thumb(150, 150, \think\Image::THUMB_CENTER)->save($image_files . '_thumb.png');
					if ($bol) {
						$map['url'] = $imgurls;
						$map['name'] = $imgname;
						$map['thumb'] = $request->domain() . $image_file . '_thumb.png';
						$map['base_image'] = date("Y-m-d") . '/' . $imgname;
						$data['code'] = 666;
						$data['msg'] = "上传成功！";
						$data['data'] = $map;
					} else {
						$data['code'] = 30020;
						$data['msg'] = "上传失败！";
						$data['data'] = '';
					};
				};
			} else {
				// 不是图片类型
				$data['code'] = 30019;
				$data['msg'] = "没有图片，再检查一下吧！";
				$data['data'] = '';
			};
		} else {
			// 失败
			$data['code'] = 30020;
			$data['msg'] = "上传失败！";
			$data['data'] = '';
		};
		return $data;
		//exit;
	}

	// 上传商户认证信息图片
	// Jason
	// 2018-08-31
	public function uploadMerchant() {

		$request = Request::instance();
		// 接收文件
		$keys = array_keys($_FILES);
		$key = $keys['0'];
		$file = $_FILES[$key];

		// 先判断有没有错
		if ($file["error"] == 0) {
			$typeArr = explode("/", $file["type"]);

			if ($typeArr[0] == "image") {
				$imgType = array("png", "jpg", "jpeg");

				if (in_array($typeArr[1], $imgType)) {
					$url = "/home/resource/";
					$url2 = $_SERVER['DOCUMENT_ROOT'] . "/api/public/uploads/";
					if (!is_dir($url . date("Y-m-d"))) {
						mkdir($url . date("Y-m-d"), 0777, true);
					}
					if (!is_dir($url2 . date("Y-m-d"))) {
						mkdir($url2 . date("Y-m-d"), 0777, true);
					}
					$imgname = "";
					$imgurl = "";
					$map = array();
					$imgname = time() . "." . $typeArr[1];
					$imgurl = $url . date("Y-m-d") . '/' . $imgname;
					$imgurl2 = $url2 . date("Y-m-d") . '/' . $imgname;
					//$imgurls = "/api/public/uploads/".date("Y-m-d").'/'.$imgname;
					$bol = move_uploaded_file($file["tmp_name"], $imgurl);
					copy($imgurl, $imgurl2);
					$image = \think\Image::open($imgurl);
					$image_files = substr($imgurl, 0, strripos($imgurl, '.'));
					$image_file = substr($image_files, strrpos($imgurl, 'api') - 1);
					$image->thumb(150, 150, \think\Image::THUMB_CENTER)->save($image_files . '_thumb.png');
					if ($bol) {
						$map['url'] = $request->domain() . "/api/public/uploads/" . date("Y-m-d") . '/' . $imgname;
						$map['name'] = $imgname;
						$map['thumb'] = $url . date("Y-m-d") . '/' . $image_file . '_thumb.png';
						$map['base_image'] = date("Y-m-d") . '/' . $imgname;
						$data['code'] = 666;
						$data['msg'] = "上传成功！";
						$data['data'] = $map;
					} else {
						$data['code'] = 30020;
						$data['msg'] = "上传失败！";
						$data['data'] = '';
					};
				};
			} else {
				// 不是图片类型
				$data['code'] = 30019;
				$data['msg'] = "没有图片，再检查一下吧！";
				$data['data'] = '';
			};
		} else {
			// 失败
			$data['code'] = 30020;
			$data['msg'] = "上传失败！";
			$data['data'] = '';
		};
		return $data;
		//exit;
	}
	/**
	 * 刘家腾
	 * 2018-5-7
	 * 获取商户旗下所有店铺
	 */
	public function shops() {
		$userinfo = $this->user;

		if ($userinfo['is_business'] == 1) {
			return Db::table('store')
				->where('business_id', $userinfo['id'])
				->where('state', 0)
				->field('business_id,user_id as store_id,store_name')
				->select();
		}
		if ($userinfo['shop'] == 1) {
			return Db::table('store')
				->where('user_id', $userinfo['id'])
				->where('state', 0)
				->field('business_id,user_id as store_id,store_name')
				->select();
		}
		if ($userinfo['is_staff'] == 1) {
			return Db::table('staff')
				->alias('sta')
				->join('store sto', 'sta.user_id = sto.user_id', "LEFT")
				->where('sta.user_id', $userinfo['id'])
				->where('sta.state', 0)
				->field('sta.business_id,sta.user_id as store_id,sto.store_name')
				->select();
		}

	}
	/**
	 * 刘家腾
	 * 2018-5-7
	 * 获取商户旗下所有职务
	 */
	public function positions() {
		$userinfo = $this->user;

		if ($userinfo['is_business'] == 1) {
			return Db::table('haracter')
				->where('business_id', $userinfo['id'])
				->where('state', 0)
				->field('id,business_id,store_id,job_title,type')
				->select();
		}
		if ($userinfo['shop'] == 1) {
			return Db::table('haracter')
				->where('store_id', $userinfo['id'])
				->where('state', 0)
				->field('id,business_id,store_id,job_title,type')
				->select();
		}
		if ($userinfo['is_staff'] == 1) {
			return Db::table('staff')
				->alias('sta')
				->join('haracter h', 'sta.store_id = h.store_id', "LEFT")
				->where('sta.user_id', $userinfo['id'])
				->where('sta.state', 0)
				->field('h.id,sta.business_id,h.store_id,h.job_title,h.type')
				->select();
		}

	}
	/**
	 * 刘家腾
	 * 2018-5-7
	 * 获取商户旗下所有部门
	 */
	public function departments() {
		$userinfo = $this->user;

		if ($userinfo['is_business'] != 0) {
			$business_id = $userinfo['id'];
		}
		if ($userinfo['shop'] == 1) {
			$business_ids = Db::table('store')
				->where('user_id', $userinfo['id'])
				->where('state', 0)
				->field('business_id')
				->select();
			$business_id = $business_ids['0']['business_id'];
		}
		if ($userinfo['is_staff'] == 1) {
			$business_ids = Db::table('staff')
				->where('user_id', $userinfo['id'])
				->where('state', 0)
				->field('business_id')
				->select();
			$business_id = $business_ids['0']['business_id'];
		}
		return Db::table('department')
			->where('business_id', $business_id)
			->where('state', 0)
			->select();

	}

	/**
	 * 刘家腾
	 * 2018-5-7
	 * 添加员工初始化数据
	 */
	public function staff_Initialization() {

		$data['code'] = 666;
		$data['msg'] = "成功！";
		$data['data'] = '';
		$this->user_id = 36;
		$list['shops'] = $this->shops();
		$list['positions'] = $this->positions();
		$list['departments'] = $this->departments();
		$data['data'] = $list;
		if (!isset($list)) {
			$data['code'] = 30003;
			$data['msg'] = "缺少必须参数！";
			$data['data'] = '';
		}
		return $data;
	}
	/**
	 * 刘家腾
	 * 2018-4-30
	 * 结算
	 */
	public function settlement() {
		$data['code'] = 666;
		$data['msg'] = "成功！";
		$data['data'] = '';
		$map = array();
		$datas = array();
		$datas = input('post.');
		$map['info_batchcode'] = $datas['info_batchcode'];
		if (empty($datas['info_batchcode'])) {
			$data['code'] = 30013;
			$data['msg'] = "缺少订单详情编号！";
		} else {
			$map['state'] = 0;
		}

		// if(empty($datas['batchcode'])){
		//   $data['code']=30014;
		//   $data['msg']="缺少订单通用编号！";
		// }else{
		//  $map['batchcode']=$datas['batchcode'];
		// }

		$info_confirm = Db::table('orders_info')->where($map)->find();
		/**
		 * 查询订单状态
		 */
		if ($info_confirm['is_settlement'] == 1) {
			$data['code'] = 30015;
			$data['msg'] = "不能重复结算！";
		}
		if ($info_confirm['state'] == 1) {
			$data['code'] = 30016;
			$data['msg'] = "无效订单号！";
		}
		if ($data['code'] == 666) {

			$is_confirm = Db::table('orders_info')->where($map)->update(['is_settlement' => 1, 'last_time' => date('Y-m-d H:i:s')]);

			if ($is_confirm < 1) {
				$data['code'] = 30017;
				$data['msg'] = "未知网络错误 结算失败！";
			} else {
				$orders_infos = Db::table('orders_info')->where(['info_batchcode' => $datas['info_batchcode']])->find();

				$orders = Db::table('orders')->where(['batchcode' => $orders_infos['batchcode']])->find();
				OL::insert([
					'user_id' => $this->user_id,
					'module' => 'orders',
					'module_id' => $orders['id'],
					'operation_type' => 2, //操作类型：1增加2修改3禁用4删除5登录6登出7导出8待添加
					'operation_content' => json_encode(['orders' => $orders]),
				]);

				OL::insert([
					'user_id' => $this->user_id,
					'module' => 'orders',
					'module_id' => $orders_infos['id'],
					'operation_type' => 2, //操作类型：1增加2修改3禁用4删除5登录6登出7导出8待添加
					'operation_content' => json_encode(['orders_info' => $orders_infos]),
				]);
			}
		}
		return $data;
	}

	/**
	 *pages 总页数
	date_count 总条数
	page 当前页
	single_page 一页多少条
	 *刘家腾
	 *2018-4-28
	 * 商品结算明细
	 */
	public function settlement_details() {
		$data['code'] = 666;
		$data['msg'] = "商品结算明细获取成功！";
		$data['data'] = '';
		$a = 0;
		$userinfo = $this->user;
		if ($userinfo['is_business'] > 0) {
			$map['o.business_id'] = $userinfo['id'];
			$a = 1;
		}
		if ($userinfo['shop'] > 0) {
			$map['o.store_id'] = $userinfo['id'];
			$a = 1;
		}
		if ($a == 0) {
			$staffinfo = $this->getbusinessid($userinfo['id']);
			$map['o.business_id'] = $staffinfo['0']['business_id'];
			$map['o.store_id'] = $staffinfo['0']['store_id'];
		}
		$map['o.state'] = 0;
		$dates = input('post.');
		$userinfo = $this->user;
		$system_id = $userinfo['system_id'];
		$page = isset($dates['page']) ? $dates['page'] : 0;

		$batchcode = isset($dates['batchcode']) ? $dates['batchcode'] : 0;
		$birthday = isset($dates['birthday']) ? $dates['birthday'] : 0;
		$between = isset($dates['between']) ? $dates['between'] : 0;
		$single_page = isset($dates['single_page']) ? $dates['single_page'] : 0;
		$page = isset($dates['page']) ? $dates['page'] : 0;
		if ($page >= 1) {
			$page = $page - 1;
		}
		$single_page = $single_page == 0 ? 20 : $single_page;
		$map['o.system_id'] = $system_id;
		$map['o.is_settlement'] = 1;
		$map['o.state'] = 0;
		if ($birthday == 0 && $between == 0 && $batchcode == 0) {
			$date_count = Db::table('orders_info')
				->alias('o')
				->join('user_info ui', 'o.customer_id = ui.id', "LEFT")
				->join('bankcard b', 'o.customer_id = b.user_id', "LEFT")
				->where($map)
				->order('o.id desc')
				->count();
			$pages = ceil($date_count / $single_page);
			$datalist = Db::table('orders_info')
				->alias('o')
				->join('orders os', 'o.batchcode = os.batchcode', "LEFT")
				->join('user_info ui', 'o.customer_id = ui.id', "LEFT")
				->join('bankcard b', 'o.customer_id = b.user_id', "LEFT")
				->join('product p', 'o.product_id = p.id', "LEFT")
				->join('product_fineness pf', 'p.product_condition = pf.id', 'LEFT')
				->join('sales_condition sc', 'sc.id = o.status', 'LEFT')
				->field('o.status,sc.value status_value,o.batchcode,o.product_name,p.product_sn,p.pic_url,p.systematics_id,p.product_condition,pf.value product_condition_value,o.cost_price,o.order_source,os.cover,o.createtime,o.is_settlement,ui.wechat,ui.alipay,b.bankcard_id,o.is_settlement')
				->where($map)
				->order('o.id desc')
				->limit($page * $single_page, $single_page)
				->select();
		} else {
			if ($batchcode != 0) {
				$map['o.batchcode'] = $batchcode;
			}
			if ($birthday == 0) {
				$birthday = "2018-3-20";
			}
			if ($between == 0) {
				$between = date("Y-m-d");
			}
			$date_count = Db::table('orders_info')
				->alias('o')
				->join('user_info ui', 'o.customer_id = ui.id', "LEFT")
				->join('bankcard b', 'o.customer_id = b.user_id', "LEFT")
				->where($map)
				->order('o.id desc')
				->count();
			$pages = ceil($date_count / $single_page);
			$datalist = Db::table('orders_info')
				->alias('o')
				->join('orders os', 'o.batchcode = os.batchcode', "LEFT")
				->join('user_info ui', 'o.customer_id = ui.id', "LEFT")
				->join('bankcard b', 'o.customer_id = b.user_id', "LEFT")
				->join('product p', 'o.product_id = p.id', "LEFT")
				->join('product_fineness pf', 'p.product_condition = pf.id', 'LEFT')
				->join('sales_condition sc', 'sc.id = o.status', 'LEFT')
				->field('o.status,sc.value status_value,o.batchcode,o.product_name,p.product_sn,p.pic_url,p.systematics_id,p.product_condition,pf.value product_condition_value,o.cost_price,o.order_source,os.cover,o.createtime,o.is_settlement,ui.wechat,ui.alipay,b.bankcard_id,o.is_settlement')
				->where($map)
				->where('o.createtime', 'between time', [$birthday, $between])
				->order('o.id desc')
				->limit($page * $single_page, $single_page)
				->select();
		}
		if (!$datalist) {
			$data['code'] = 666;
			$data['msg'] = "未获取到商品结算明细！";
		} else {
			foreach ($datalist as $key => $value) {
				$product = new \app\index\controller\Product();
				$systematics_arr = $product->set_product_name($value['systematics_id']);
				if (!$systematics_arr['data']) {
					$datalist[$key]['pre_name'] = '';
				} else {
					$datalist[$key]['pre_name'] = $systematics_arr['data'];
				}
			}

		}

		$data['pages'] = $pages;
		$data['date_count'] = $date_count;
		$data['single_page'] = $single_page;
		$data['page'] = $page + 1; //当前页
		$data['data'] = $datalist;

		return $data;

	}

	/**
	 * 刘家腾
	 * 2018-4-28
	 * 商品结算列表
	 */
	public function commodity_settlement() {
		$data['code'] = 666;
		$data['msg'] = "商品结算列表获取成功！";
		$data['data'] = '';
		$a = 0;
		$userinfo = $this->user;
		if ($userinfo['is_business'] > 0) {
			$map['o.business_id'] = $userinfo['id'];
			$a = 1;
		}
		if ($userinfo['shop'] > 0) {
			$map['o.store_id'] = $userinfo['id'];
			$a = 1;
		}
		if ($a == 0) {
			$staffinfo = $this->getbusinessid($userinfo['id']);
			$map['o.business_id'] = $staffinfo['0']['business_id'];
			$map['o.store_id'] = $staffinfo['0']['store_id'];
		}
		$dates = input('post.');
		$system_id = $userinfo['system_id'];
		$page = isset($dates['page']) ? $dates['page'] : 0;
		if ($page >= 1) {
			$page = $page - 1;
		}
		$batchcode = isset($dates['batchcode']) ? $dates['batchcode'] : 0;
		$birthday = isset($dates['birthday']) ? $dates['birthday'] : 0;
		$between = isset($dates['between']) ? $dates['between'] : 0;
		$single_page = 20;
		$map['o.system_id'] = $system_id;
		$map['o.state'] = 0;
		$map['o.is_settlement'] = 0;

		if ($birthday == 0 && $between == 0 && $batchcode == 0) {
			$date_count = Db::table('orders_info')
				->alias('o')
				->join('user_info ui', 'o.customer_id = ui.id', "LEFT")
				->join('bankcard b', 'o.customer_id = b.user_id', "LEFT")
				->join('product p', 'o.product_id = p.id', "LEFT")
				->join('product_fineness pf', 'p.product_condition = pf.id', 'LEFT')
				->where($map)
				->order('o.id desc')
				->count();

			$datalist = Db::table('orders_info')
				->alias('o')
				->join('orders os', 'o.batchcode = os.batchcode', "LEFT")
				->join('user_info ui', 'o.customer_id = ui.id', "LEFT")
				->join('bankcard b', 'o.customer_id = b.user_id', "LEFT")
				->join('product p', 'o.product_id = p.id', "LEFT")
				->join('product_fineness pf', 'p.product_condition = pf.id', 'LEFT')
				->join('sales_condition sc', 'sc.id = o.status', 'LEFT')
				->field('o.id,o.batchcode,o.info_batchcode
				,o.product_name,o.original_price,p.product_sn,p.product_source,p.pic_url,p.systematics_id,p.product_condition,o.order_source,o.status,sc.value status_value,os.cover,o.createtime,o.is_settlement,pf.value product_condition_value')
				->where($map)
				->order('o.id desc')
				->limit($page * $single_page, $single_page)
				->select();
		} else {
			if ($batchcode != 0) {
				$map['o.batchcode'] = $batchcode;
			}
			if ($birthday == 0) {
				$birthday = "2018-3-20";
			}
			if ($between == 0) {
				$between = date("Y-m-d");
			}

			$date_count = Db::table('orders_info')
				->alias('o')
				->join('user_info ui', 'o.customer_id = ui.id', "LEFT")
				->join('bankcard b', 'o.customer_id = b.user_id', "LEFT")
				->join('product p', 'o.product_id = p.id', "LEFT")
				->join('product_fineness pf', 'p.product_condition = pf.id', 'LEFT')
			// ->field('o.batchcode,o.product_name,o.cost_price,o.order_source,o.cover,o.createtime,o.is_settlement')
				->where($map)
				->where('o.createtime', 'between time', [$birthday, date('Y-m-d', strtotime("$between +1 day"))])
				->order('o.id desc')
				->count();

			$datalist = Db::table('orders_info')
				->alias('o')
				->join('orders os', 'o.batchcode = os.batchcode', "LEFT")
				->join('user_info ui', 'o.customer_id = ui.id', "LEFT")
				->join('bankcard b', 'o.customer_id = b.user_id', "LEFT")
				->join('product p', 'o.product_id = p.id', "LEFT")
				->join('product_fineness pf', 'p.product_condition = pf.id', 'LEFT')
				->join('sales_condition sc', 'sc.id = o.status', 'LEFT')
				->field('o.id,o.batchcode,o.info_batchcode
				,o.product_name,o.original_price,p.product_sn,p.product_source,p.pic_url,p.systematics_id,o.status,sc.value status_value,p.product_condition,o.order_source,os.cover,o.createtime,o.is_settlement,pf.value product_condition_value')
				->where($map)
				->where('o.createtime', 'between time', [$birthday, date('Y-m-d', strtotime("$between +1 day"))])
				->order('o.id desc')
				->limit($page * $single_page, $single_page)
				->select();
		}
		if (!$datalist) {
			$data['code'] = 666;
			$data['msg'] = "商品结算列表为空！";
		} else {
			$product = new \app\index\controller\Product();
			foreach ($datalist as $pkey => $pvalue) {
				$systematics_arr = $product->set_product_name($pvalue['systematics_id']);
				if (!$systematics_arr['data']) {
					$datalist[$pkey]['pre_name'] = '';
				} else {
					$datalist[$pkey]['pre_name'] = $systematics_arr['data'];
				}
			}
		}

		$pages = ceil($date_count / $single_page);
		$data['data'] = $datalist;
		$data['pages'] = $pages; //总页数
		$data['date_count'] = $date_count; //总条数
		$data['page'] = $page + 1; //当前页
		$data['single_page'] = $single_page; //每页数量
		return $data;

	}
	/**
	 * 刘家腾
	 * 2018-4-28
	 * 商品结算详情
	 */
	public function settlement_info() {
		$data['code'] = 666;
		$data['msg'] = "商品结算详情获取成功！";
		$data['data'] = '';
		$page = 0;
		$single_page = 3;
		$map['o.system_id'] = $this->system_id;
		$map['o.batchcode'] = input('post.batchcode');
		$map['o.state'] = 0;
		if ($map['o.batchcode'] == '') {
			$data['code'] = 30003;
			$data['msg'] = "缺少核心参数！";
			$data['data'] = '';
		}
		$datalist = Db::table('orders_info')
			->alias('o')
			->join('user_info ui', 'o.customer_id = ui.id', "LEFT")
			->join('staff s', 'o.staff_id = s.user_id', "LEFT")
			->join('bankcard b', 'o.customer_id = b.user_id', "LEFT")
			->join('product p', 'o.product_id = p.id', "LEFT")
			->join('product_fineness pf', 'p.product_condition = pf.id', 'LEFT')
			->field('o.id,o.product_id,o.product_name,p.systematics_id,p.product_condition,pf.value product_condition_value,o.other_fee,o.price,o.cost_price,o.createtime,o.pay_reatetime,o.info_batchcode,p.product_source,ui.wechat,ui.alipay,b.bankcard_id,o.is_settlement,o.staff_id,s.name staff_name,o.real_profit,o.sale_profit,o.collect_profit')
			->where($map)
			->order('o.id desc')
			->limit($page, $single_page)
			->select();

		if (!$datalist) {
			$data['code'] = 30009;
			$data['msg'] = "订单号不存在！";
		} else {
			$product = new \app\index\controller\Product();
			foreach ($datalist as $pkey => $pvalue) {
				$systematics_arr = $product->set_product_name($pvalue['systematics_id']);
				if (!$systematics_arr['data']) {
					$datalist[$pkey]['pre_name'] = '';
				} else {
					$datalist[$pkey]['pre_name'] = $systematics_arr['data'];
				}
			}
		}
		$data['data'] = $datalist;

		return $data;

	}

	/**
	 * 刘家腾
	 * 2018-4-28
	 * 商品结算-删除
	 */
	public function settlement_delete() {
		$data['code'] = 666;
		$data['msg'] = "商品结算删除！";
		$data['data'] = '';
		$dates = input('post.batchcode');

		if ($dates == '') {
			$data['code'] = 30003;
			$data['msg'] = "参数错误！";
		}
		if ($data['code'] == 666) {
			$map['batchcode'] = $dates;
			$map['state'] = 0;
			$is_delete = Db::table('orders')->where($map)->update(['state' => '1']);
			if ($is_delete != 1) {
				$data['code'] = 30004;
				$data['msg'] = "删除失败！";
			}
		}
		return $data;

	}

	/**
	 * 刘家腾
	 * 2018-4-25
	 * 过滤未定义变量
	 */
	public function is_isset($value = '', $date = '') {
		$list = explode(',', $value);
		foreach ($list as $key => $v) {
			$data["$v"] = isset($date["$v"]) ? $date["$v"] : '0';
		}
		return $data;
	}

	/**
	 * 刘家腾
	 * 2018-4-25
	 * 员工列表
	 */
	public function staff_list() {
		//初始化参数
		$data['code'] = 666;
		$data['msg'] = '员工列表数据获取成功！';
		$data['data'] = '';
		$single_page = 20; //单页数
		$mapor = [];
		$userinfo = $this->user;
		$dates = input('post.');

		$issetdate = 'system_id,business_id,shop_id,page,shop_name,position_id,name,phone,page';
		$date = self::is_isset($issetdate, $dates);

		if ($date['system_id'] != 0 && $userinfo['system_id'] != $date['system_id']) {
			$data['code'] = 30003;
			$data['msg'] = '缺少必须参数！系统ID错误！';
		}

		$map['u.system_id'] = $userinfo['system_id'];
		$map['s.is_delete'] = 0;

		if ($userinfo['is_business'] != 1) {
//商户
			$map['s.business_id'] = $userinfo['id'];
			if ($date['shop_id'] != 0) {
				$map['s.store_id'] = $date['shop_id'];
			}
		} elseif ($userinfo['shop'] == 1) {
//门店
			$business_info = $this->get_businessid($userinfo['id']);
			$map['s.business_id'] = $business_info;
			$map['s.store_id'] = $userinfo['id'];
		} elseif ($userinfo['is_staff'] == 1) {
//员工
			$business_info = $this->getbusinessid($userinfo['id']);
			$map['s.business_id'] = $business_info['0']['business_id'];
			if ($business_info['0']['store_id'] != 0) {
				$map['s.store_id'] = $business_info['0']['store_id'];
			}
		}

		if ($date['shop_name']) {
			$mapor['st.store_name'] = ['like', '%' . $date['shop_name'] . '%'];
			$mapor['b.business_name'] = ['like', '%' . $date['shop_name'] . '%'];
		}
		if ($date['position_id']) {
			$mapor['s.position_id'] = ['like', '%' . $date['position_id'] . '%'];
		}

		if ($date['name']) {
			$mapor['s.name'] = ['like', '%' . $date['name'] . '%'];
		}
		if ($date['phone']) {
			$mapor['u.phone'] = ['like', $date['phone']];
		}
		//$map['s.state']=0;
		$page = $date['page'] - 1;
		if ($page < 0) {
			$page = 0;
		}

		$map['u.is_customer'] = 0;
		$map['u.is_staff'] = 1;
		$map['s.business_id'] = $this->business_id;
		if (empty($mapor)) {
			$date_count = Db::table('staff')
				->alias('s')
				->join('users u', 'u.id = s.user_id', 'LEFT')
				->join('business b', 's.business_id = b.business_id', 'LEFT')
				->join('store st', 's.store_id = st.user_id', 'LEFT')
				->join('department d', 's.department_id = d.id', 'LEFT')
				->join('haracter h', 's.position_id = h.id', 'LEFT') //职位
				->where($map)
				->count();

			$datalist = Db::table('staff')
				->alias('s')
				->join('users u', 'u.id = s.user_id', 'LEFT')
				->join('business b', 's.business_id = b.business_id', 'LEFT')
				->join('store st', 's.store_id = st.user_id', 'LEFT')
				->join('department d', 's.department_id = d.id', 'LEFT')
				->join('haracter h', 's.position_id = h.id', 'LEFT') //职位
				->where($map)
				->field('s.id,s.user_id,s.name,s.phone,b.business_name, st.store_name,s.createtime,d.title,h.job_title,s.state')
				->order('s.user_id desc')
				->limit($page * $single_page, $single_page)
				->select();
			//$data['sql']=Db::table('staff')->getLastSql();

		} else {

			$date_count = Db::table('staff')
				->alias('s')
				->join('users u', 'u.id = s.user_id', 'LEFT')
				->join('business b', 's.business_id = b.business_id', 'LEFT')
				->join('store st', 's.store_id = st.user_id', 'LEFT')
				->join('department d', 's.department_id = d.id', 'LEFT')
				->join('haracter h', 's.position_id = h.id', 'LEFT') //职位
				->where($map)
				->where(function ($query) use ($mapor) {
					$query->whereOr($mapor);
				})
				->count();

			$datalist = Db::table('staff')
				->alias('s')
				->join('users u', 'u.id = s.user_id', 'LEFT')
				->join('business b', 's.business_id = b.business_id', 'LEFT')
				->join('store st', 's.store_id = st.user_id', 'LEFT')
				->join('department d', 's.department_id = d.id', 'LEFT')
				->join('haracter h', 's.position_id = h.id', 'LEFT') //职位
				->where($map)
				->where(function ($query) use ($mapor) {
					$query->whereOr($mapor);
				})
				->field('s.user_id,s.name,s.phone,b.business_name,st.store_name,s.createtime,d.title,h.job_title,s.state')
				->order('s.user_id desc')
				->limit($page * $single_page, $single_page)
				->select();
			//$data['sql']=Db::table('staff')->getLastSql();

		}

		$pages = ceil($date_count / $single_page);

		$page = $date['page'] == 0 || $date['page'] == 1 ? 0 : ($date['page'] - 1) * $single_page;

		if ($data['code'] == 666) {

			if ($date['page'] > $pages) {
				$data['code'] = 30004;
				$data['msg'] = '请求页数错误！';
			}
			if ($date_count == 0) {
				$data['code'] = 666;
				$data['msg'] = '使出洪荒之力也没有你想要的数据！';
			}
			$data['data'] = $datalist;
			$data['pages'] = $pages; //总页数
			$data['date_count'] = $date_count; //总条数
			$data['page'] = $page + 1; //当前页
			$data['single_page'] = $single_page; //每页数量
		}
		return $data;
	}
	/**
	 * 刘家腾
	 * 2018-4-25
	 * @return     检测是否有相同的账号标识
	 *
	 */
	public function is_user($date) {

		return Db::table('users')->alias('u')
			->where('u.phone', $date['phone'])
			->where('u.is_business|u.shop|u.is_staff', 1)
			->count();
	}
	/**
	 * 刘家腾
	 * 2018-4-25
	 * @return     查询用户详情
	 *
	 */
	public function is_users($date) {
		$map['id'] = $date['id'];
		$map['phone'] = $date['phone'];
		return Db::table('users')
			->whereor(["id" => $map['id']])
			->whereor(["phone" => $map['phone']])
			->where(["state" => 0])
			->select();
		// return Db::table('users')
		//   ->where([ "is_staff" =>1 ])
		//   ->where(function($db) use ($map){
		//         $db->whereor(["id"=>$map['id']])
		//         ->whereor(["phone"=>$map['phone']])
		//         ->whereor(["openid"=>$map['openid']])
		//         ->whereor(["unionid"=>$map['unionid']]);
		//     }) ->select();
	}

	/**
	 * 刘家腾
	 * 2018-5-14
	 * 获取员工详情
	 */
	public function get_staff() {
		$data['code'] = 666;
		$data['msg'] = "成功获取员工详情！";
		$data['data'] = '';
		$date = input('post.');
		$rule = [
			'user_id' => 'require',
		];
		if ($this->validate($date, $rule) !== true) {
			return ['code' => 30001, 'msg' => $this->validate($date, $rule)];
		}

		$data['data'] = Db::table('staff')
			->alias('s')
			->join('users u', 's.user_id = u.id', 'LEFT')
			->join('user_info ui', 's.user_id = ui.user_id', 'LEFT')
			->join('business b', 's.business_id = b.business_id', 'LEFT')
			->join('store st', 's.store_id = st.id', 'LEFT')
			->join('department d', 's.department_id = d.id', 'LEFT')
			->join('haracter h', 's.position_id = h.id', 'LEFT') //职位
			->where(["s.state" => 0])
			->where(["s.is_delete" => 0])
			->where(["s.user_id" => $date['user_id']])
			->field('u.id, s.name,ui.sex,s.phone,u.password,s.supervisor_id superior_id
				, s.business_id,s.is_hire, s.store_id, st.store_name,st.createtime,s.department_id,d.title, s.position_id, h.job_title')
			->select();
		if (!$data['data']) {
			$data['code'] = 30023;
			$data['msg'] = "未获取到员工详情！";
			$data['data'] = '';
		}
		return $data;
	}
	/**
	 *刘家腾
	 *2018-4-25
	 *添加员工
	 */
	public function staff_add(Request $request) {
		$postData = $request->post();

		$rules = [
			'business_id|商户ID' => 'require',
			'name' => 'require',
			'sex' => 'integer',
			'phone' => 'require|number',
			'password' => 'require',
			'password2' => 'require',
			'superior_id' => 'integer',
			'position_id' => 'integer',
			'department_id' => 'integer',
			'is_hire' => 'integer',
			'store_id' => 'integer',
		];

		if (isset($postData['id']) && $postData['id'] !== null) {
			return $this->staff_update($postData);
		}

		if ($this->validate($postData, $rules) === true) {
			if ($postData['password'] !== $postData['password2']) {
				return ReturnData::error(30003, '两次密码不一致');
			}

			//DB::startTrans();

			$userinfo = $this->user;

			$userdata['id'] = isset($postData['user_id']) ? $postData['user_id'] : '0';
			$userdata['phone'] = isset($postData['phone']) ? $postData['phone'] : '0';
			$userdata['openid'] = isset($postData['openid']) ? $postData['openid'] : '0';
			$userdata['unionid'] = isset($postData['unionid']) ? $postData['unionid'] : '0';
			$userdata['is_business'] = 1;
			$userdata['shop'] = 1;
			$userdata['is_staff'] = 1;

			$userinfos = self::is_user($userdata); //查询输入手机号是否已存在
			if ($userinfo['is_business'] == 1) {
//商户
				$businessid = $userinfo['id'];
				$store_id = isset($postData['store_id']) ? $postData['store_id'] : 0;
			} elseif ($userinfo['shop'] == 1) {
//门店
				$businessid = $this->get_businessid($userinfo['id']);
				$store_id = $userinfo['id'];
			} elseif ($userinfo['is_staff'] == 1) {
//员工
				$list = $this->getbusinessid($userinfo['id']);
				$businessid = $list['0']['business_id'];
				$store_id = $list['0']['store_id'];
			}
			//初始化 users表 参数
			if ($userinfos == 0) {
				$usdate['is_business'] = 0;
				$usdate['shop'] = 0;
				$usdate['grade'] = 0;
				$usdate['agent'] = 0;
				$usdate['state'] = 0;
				$usdate['gene'] = '-1,';
				$usdate['is_address'] = 0;
				$usdate['is_details'] = 0;
				$usdate['couponss'] = 0;

				$usdate['is_identity'] = 0;
				$usdate['is_bankcard'] = 0;
				$usdate['is_customer'] = 0;
				$usdate['createtime'] = date('Y-m-d H:i:s');
				//接收传递参数
				$usdate['business_id'] = $businessid;
				$usdate['name'] = $postData['name'];
				$usdate['phone'] = $postData['phone'];
				$usdate['password'] = $postData['password'];
				$usdate['system_id'] = $userinfo['system_id'];
				//$usdate['supervisor_id']=isset($date['superior_id'])?$date['superior_id']:'-1';
				$usdate['is_staff'] = 1; //是否员工
				$userId = Db::table('users')->data($usdate)->insert();
				$insert_id = Db::table('users')->getLastInsID(); //获取刚插入数据的id
				$userlist['user_id'] = $insert_id == "" ? $userdata['id'] : $insert_id;

				$userlist['name'] = $postData['name'];
				$userlist['sex'] = isset($postData['sex']) ? $postData['sex'] : 3;
				$userinfo_id = Db::table('user_info')->data($userlist)->insert();

				$staffdate['business_id'] = $businessid;
				$staffdate['store_id'] = $store_id; //门店
				$staffdate['user_id'] = $insert_id;
				$staffdate['name'] = $postData['name'];
				$staffdate['phone'] = $postData['phone'];
				$staffdate['position_id'] = $postData['position_id']; //职位
				$staffdate['department_id'] = $postData['department_id']; //部门
				$staffdate['supervisor_id'] = isset($postData['superior_id']) ? $postData['superior_id'] : '-1';
				$staffdate['is_hire'] = $postData['is_hire']; //是否外聘
				$staffdate['createtime'] = date('Y-m-d H:i:s');
				$staff_id = Db::table('staff')->data($staffdate)->insert();

				if ($userId == '' || $userinfo_id == '' || $staff_id == '') {
					//Db::rollback();
					return ReturnData::error(30001, 'database error');
				}
				// Db::commit();
				OL::insert([
					'user_id' => $this->user_id,
					'module' => 'staff',
					'module_id' => $userId,
					'operation_type' => 1, //操作类型：1增加2修改3禁用4删除5登录6登出7导出8待添加
					'operation_content' => json_encode(['staff' => Db::table('staff')->where(['user_id' => $userId])->find()]),
				]);
				return ReturnData::ok();

			} else {
				if (isset($postData['id']) && $postData['id'] !== null) {
					return $this->staff_update($postData);
				} else {
					return ReturnData::error(30001, '该手机号已经是商家或门店或员工');
				}
			}

		} else {
			return ReturnData::error(10003, $this->validate($postData, $rules));
		}

	}

	public function staff_update($postData) {
		$rules = [
			'name' => 'require',
			'sex' => 'integer',
			'superior_id' => 'integer',
			'position_id' => 'integer',
			'department_id' => 'integer',
			'is_hire' => 'integer',
			'store_id' => 'integer',
		];
		if ($this->validate($postData, $rules) === true) {
			$userinfo = $this->user;

			// $userdata['id']=isset($postData['user_id'])?$postData['user_id']:'0';
			// $userdata['phone']=isset($postData['phone'])?$postData['phone']:'0';
			// $userdata['openid']=isset($postData['openid'])?$postData['openid']:'0';
			// $userdata['unionid']=isset($postData['unionid'])?$postData['unionid']:'0';

			if ($userinfo['is_business'] == 1) {
//商户
				$businessid = $userinfo['id'];
				$store_id = isset($postData['store_id']) ? $postData['store_id'] : 0;
			} elseif ($userinfo['shop'] == 1) {
//门店
				$businessid = $this->get_businessid($userinfo['id']);
				$store_id = $userinfo['id'];
			} elseif ($userinfo['is_staff'] == 1) {
//员工
				$list = $this->getbusinessid($userinfo['id']);
				$businessid = $list['0']['business_id'];
				$store_id = $list['0']['store_id'];
			}
			//接收传递参数
			$userId = Db::table('users')->where('id', $postData['id'])->update(['name' => $postData['name']]);

			$sex = isset($postData['sex']) ? $postData['sex'] : 3;
			$userinfo_id = Db::table('user_info')->where(['user_id' => $postData['id']])->update(['name' => $postData['name'], 'sex' => $sex]);
			$staffdate = [];
			$staffdate['business_id'] = $businessid;
			$staffdate['store_id'] = $store_id; //门店
			$staffdate['name'] = $postData['name'];
			$staffdate['position_id'] = $postData['position_id']; //职位
			$staffdate['department_id'] = $postData['department_id']; //部门
			$staffdate['supervisor_id'] = isset($postData['superior_id']) ? $postData['superior_id'] : '-1';
			$staffdate['is_hire'] = $postData['is_hire']; //是否外聘

			$staff_id = Db::table('staff')->where(['user_id' => $postData['id']])->update($staffdate);
			OL::insert([
				'user_id' => $this->user_id,
				'module' => 'staff',
				'module_id' => $postData['id'],
				'operation_type' => 2,
				'operation_content' => json_encode(['staff' => Db::table('staff')->where(['user_id' => $postData['id']])->find()]),
			]);

			return ReturnData::ok();
		} else {
			return ReturnData::error(10003, $this->validate($postData, $rules));
		}

	}

	/**
	 *刘家腾
	 *2018-4-25
	 *修改员工
	 */
	// public function staff_update($data)
	// {
	//   /**
	//    * 初始数据
	//    */
	//     $status = 666;
	//     DB::startTrans();
	//     //$data=input('post.');

	//     $validate=[
	//         "id|员工id"=>"require",
	//         "name"   =>"require",
	//         "password"   =>"require",
	//     ];

	//     if($this->validate($data, $validate) !== true)
	//     return ['code'=> 30003, 'msg'=>'员工id不能为空'];

	//     $userinfo=$this->user;
	//     $issetdate = 'id, system_id,sex,shop_id,position_id,superior_id,name,password,position_id,department_id,is_hire';
	//     $data=self::is_isset($issetdate,$data);

	//     $userdata['id']=isset($data['id']);
	//     $userdata['openid']=isset($data['openid'])?$data['phone']:'0';
	//     $userdata['unionid']=isset($data['unionid'])?$data['phone']:'0';

	//     if($userinfo['is_business']==1){//商户
	//      $businessid=$userinfo['id'];
	//      $store_id=0;
	//     }
	//     elseif($userinfo['shop']==1){//门店
	//      $businessid=$this->get_businessid($userinfo['id']);
	//      $store_id=$userinfo['id'];
	//     }
	//     elseif($userinfo['is_staff']==1){//员工
	//   $list=$this->getbusinessid($userinfo['id']);
	//   $businessid=$list['0']['business_id'];
	//      $store_id=$list['0']['store_id'];
	//     }

	//     $staffData = ['business_id' =>$businessid, 'store_id'=>$data['shop_id'], 'name'=>$data['name'],'position_id'=>$data['position_id'],'department_id'=>$data['department_id'], 'is_hire'=>$data['is_hire'],'supervisor_id'=>$data['superior_id'] ];
	//     if(Db::table('staff')->where("user_id",$data['id'])->update($staffData))
	//       $status =666;
	//     else
	//       Db::rollback();

	//     $userData = ['name' =>$data['name'], 'superior_id'=>$data['superior_id'], 'password'=>$data['password'] ];
	//     if(Db::table('users')->where("id",$data['id'])->update($userData))
	//       $status =666;
	//     else
	//       Db::rollback();

	//     $userInfoData = ['name' => $data['name'], 'sex' => $data['sex']];
	//     if(Db::table('user_info')->where("user_id",$data['id']) ->update($userInfoData))
	//       $status =666;
	//     else
	//       Db::rollback();

	//     Db::commit();
	//     return ['code'=> $status, 'msg'=> '修改成功'];

	// }

	/**
	 * 刘家腾
	 * 2018-4-28
	 * @return    员工 获取商户id
	 *
	 */
	public function getbusinessid($user_infoid = 0) {
		return Db::table('staff')
			->whereor(["user_id" => $user_infoid])
			->where(["state" => 0])
			->field('business_id,store_id')
			->select();
	}

	/**
	 * 刘家腾
	 * 2018-4-25
	 * @return     门店 获取商户id
	 *
	 */
	public function get_businessid($user_infoid = 0) {

		return Db::table('store')
			->where("user_id", $user_infoid)
			->where("state", 0)
			->value('business_id');
	}

	/**
	 * Jason ZHENG
	 * 2018-05-17
	 * @param id => 员工id, new_password => 新密码, new_password2 => 确认新密码
	 * @return true，false
	 *
	 */
	public function staff_pwd(Request $request) {
		$post = $request->post();
		$validate = [
			"id|员工账号" => "require",
			"new_password|新密码" => "require|max:100",
			"new_password2|确认新密码" => "require|max:100",
		];

		if ($this->validate($post, $validate) === true) {
			if ($post['new_password'] !== $post['new_password2']) {
				return ReturnData::error(30010, '密码不一致！');
			}
			$staff = Db::table('staff')->where(['user_id' => $post['id']])->select();
			if (empty($staff)) {
				return ReturnData::error(30010, '未找到该员工！');
			} elseif (empty(Db::table('users')->where(['id' => $post['id']])->select())) {
				return ReturnData::error(30010, '未找到该用户！');
			} else {
				$staff = Db::table('users')->where(['id' => $post['id']])->update(['password' => $post['new_password']]);
				OL::insert([
					'user_id' => $this->user_id,
					'module' => 'users',
					'module_id' => $post['id'],
					'operation_type' => 2,
					'operation_content' => json_encode(['users' => Db::table('users')->where(['id' => $post['id']])->find()]),
				]);

				return ReturnData::ok();
			}
		} else {
			return ReturnData::error(30011, $this->validate($post, $validate));
		}
	}
}
